package cn.edu.interceptor;

import cn.edu.util.JwtUtil;
import cn.edu.vo.ResultVO;
import com.alibaba.fastjson.JSON;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author Mr.ma
 * @since 2022/11/23 16:00
 **/
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("application/json;charset=utf-8");
        //判断请求方式，排除OPTIONS请求
        if("OPTIONS".equals(request.getMethod().toUpperCase())){
            //通过所有OPTION请求
            return true;
        }

        String token = request.getHeader("token");
        if (StringUtils.hasText(token)){
            if (JwtUtil.verifyToken(token)){
                return true;
            }
        }
        System.out.println("token = " + token);
        PrintWriter out = response.getWriter();
        String resultJson = JSON.toJSONString(new ResultVO(4001, null, "用户未登录"));
        out.write(resultJson);
        out.flush();
        out.close();
        return false;
    }
}
